package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.RedisManager;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.handler.im_erp9.ModelHandler;
import com.innovation.ic.im.end.base.mapper.im_erp9.ChatPairMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.MessageMapper;
import com.innovation.ic.im.end.base.model.im_erp9.ChatPair;
import com.innovation.ic.im.end.base.model.im_erp9.Message;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.MessageContext;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.pojo.im_erp9.RetractionPojo;
import com.innovation.ic.im.end.base.service.im_erp9.MessageService;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.im.end.base.value.config.PictureParamConfig;
import com.innovation.ic.im.end.base.vo.im_erp9.MessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Message的具体实现类
 */
@Service
@Transactional
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Resource
    private PictureParamConfig pictureParamConfig;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private RedisManager redisManager;

    @Resource
    private ChatPairMapper chatPairMapper;

    @Resource
    private ModelHandler modelHandler;

    /**
     * 保存Message对象
     *
     * @param message
     */
    @Override
    public ServiceResult<Integer> saveMessage(Message message) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        message.setCreateTime(new Date(System.currentTimeMillis()));
        messageMapper.insert(message);

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(message.getId());
        return serviceResult;
    }

    /**
     * 获取用户的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @param fromUserAccount
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public ServiceResult<Page> page(String fromUserAccount, Integer pageSize, Integer pageNo) {
        ServiceResult<Page> serviceResult = new ServiceResult<>();

        Page<Message> pageParam = new Page<>(pageSize, pageNo);
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("from_user_account", fromUserAccount).or().eq("to_user_account", fromUserAccount);
        messageQueryWrapper.orderByDesc("create_time");
        Page<Message> page = baseMapper.selectPage(pageParam, messageQueryWrapper);

//        System.out.println("分页查询结果:"+page.getRecords());
//        System.out.println("分页总共的数据量:"+page.getTotal());
//        System.out.println("分页总共的页码数:"+page.getPages());

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(page);
        return serviceResult;
    }

    /**
     * 获取用户的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @param fromUserAccount
     * @param toUserAccount
     * @param pageSize
     * @param pageNo
     * @param type
     * @return
     */
    @Override
    public ServiceResult<List<Message>> redisPage(String fromUserAccount, String toUserAccount,
                                                  Integer pageSize, Integer pageNo, Integer type, Integer timeout) {
        ServiceResult<List<Message>> serviceResult = new ServiceResult<>();
        //获取数据集合
        List<Message> messagesList = new ArrayList<>();
        int start = pageSize * (pageNo - 1);
        ChatPair chatPair = chatPairMapper.findByFromUserAccountAndToUserAccount(fromUserAccount, toUserAccount);
        if (chatPair == null) {
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(messagesList);
            return serviceResult;
        }

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, pageSize, chatPair.getCode(), chatPair.getContentInvisibleTime(), timeout);

        //判断type 是什么返回的数据不同
        //type为0情况 全部
        if (type.equals(MessageType.ALL)) {
            List<Message> result = modelHandler.toMessageList(stringSet, fromUserAccount);
            for (int i = 0; i < result.size(); i++) {
                Message message = result.get(i);
                Integer messageType = message.getType();
                if (messageType.equals(MessageType.FILE)) {//是文件数据
                    String filePath = message.getFilePath();
                    if (filePath != null && filePath.length() != 0) {//文件名不为空
                        String substring = filePath.substring(filePath.lastIndexOf("/") + 1);
                        result.get(i).setFilePath(substring);
                    }
                }
            }
            // 处理list中的图片数据
            handListPictureData(result);
            //进行list集合排序（升序）
            result.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(result);
            return serviceResult;
        } else if (type.equals(MessageType.FILE)) {//type为2 文件
            //存入数据
            messagesList = modelHandler.toMessageList(stringSet, fromUserAccount);
            //创建一个空的集合进行存储文件数据
            List<Message> newMessagesList = new ArrayList<>();
            for (int i = 0; i < messagesList.size(); i++) {
                //获取当中每一个type进行判断 如果是文件就返回
                Integer messagesType = messagesList.get(i).getType();
                if (messagesType.equals(MessageType.FILE)) {
                    String filePath = messagesList.get(i).getFilePath();
                    if (filePath != null && filePath.length() != 0) {//filePath不为空截取数据
                        String substring = filePath.substring(filePath.lastIndexOf("/") + 1);
                        messagesList.get(i).setFilePath(substring);
                    }
                    newMessagesList.add(messagesList.get(i));
                }
            }
            //进行list集合排序（升序）
            newMessagesList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newMessagesList);
            return serviceResult;

        } else { //type为3 图片
            //存入数据
            messagesList = modelHandler.toMessageList(stringSet, fromUserAccount);
            //创建一个空的集合进行存储图片数据
            List<Message> newMessagesList = new ArrayList<>();
            for (int i = 0; i < messagesList.size(); i++) {
                //获取当中每一个type进行判断 如果是图片就返回
                Integer messagesType = messagesList.get(i).getType();
                if (messagesType.equals(MessageType.PICTURE)) {
                    Message message = messagesList.get(i);
                    if (!Strings.isNullOrEmpty(message.getFilePath())) {
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    newMessagesList.add(message);
                }
            }
            //进行list集合排序（升序）
            newMessagesList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newMessagesList);
            return serviceResult;
        }
    }


    /**
     * 处理list中的图片数据
     *
     * @param list 结果list
     */
    private void handListPictureData(List<Message> list) {
        if (list != null && list.size() > 0) {
            for (Message message : list) {
                if (message.getType().intValue() == MessageType.PICTURE && !Strings.isNullOrEmpty(message.getFilePath())) {
                    message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                }
            }
        }
    }

    /**
     * 根据参数type和content（模糊查询），获取用户的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @return
     */
    @Override
    public ServiceResult<List<Message>> redisLikePage(MessageVo messageVo, Integer timeout) {
        ServiceResult<List<Message>> serviceResult = new ServiceResult<>();
        int start = messageVo.getPageSize() * (messageVo.getPageNo() - 1);
        //创建一个空的集合进行存数据
        List<Message> newMessagesList = new ArrayList<>();
        //去chatPair表中 查询到 对应的code
        ChatPair chatPair = chatPairMapper.findByFromUserAccountAndToUserAccount(messageVo.getFromUserAccount(), messageVo.getToUserAccount());
        if (chatPair == null) {
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newMessagesList);
            return serviceResult;
        }

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, messageVo.getPageSize(), chatPair.getCode(), chatPair.getContentInvisibleTime(), timeout);

        //数据序列化
        List<Message> messagesList = modelHandler.toMessageList(stringSet, messageVo.getFromUserAccount());
        //传递参数是否带内容如果有则模糊查询，没有则不需要
        if (StringUtils.isEmpty(messageVo.getContent())) {
            for (int i = 0; i < messagesList.size(); i++) {
                Message message = messagesList.get(i);

                // 撤回、系统的消息忽略
                if(message.getRetractionTime() != null || message.getType().equals(MessageType.SYS_MSG) || message.getType().equals(MessageType.UPDATE_USER_GROUP_NAME_SYS_MSG)){
                    continue;
                }

                //根据type不同返回不同的数据
                if (messageVo.getType().equals(MessageType.ALL)) {
                    if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messagesList.get(i).setFilePath(substring);
                    }
                    if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    newMessagesList.add(message);
                    continue;
                }
                if (messageVo.getType().equals(MessageType.FILE) && message.getType().equals(MessageType.FILE)) {
                    if (!Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messagesList.get(i).setFilePath(substring);
                    }
                    newMessagesList.add(message);
                    continue;
                }
                if (messageVo.getType().equals(MessageType.PICTURE) && message.getType().equals(MessageType.PICTURE)) {
                    if (!Strings.isNullOrEmpty(message.getFilePath())) {
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    newMessagesList.add(message);
                }
            }
            //进行list集合排序（升序）
            newMessagesList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newMessagesList);
            return serviceResult;
        } else {
            //模糊不区分大小
            Pattern pattern = Pattern.compile(messageVo.getContent(), Pattern.CASE_INSENSITIVE);
            for (int i = 0; i < messagesList.size(); i++) {
                Message message = messagesList.get(i);

                // 撤回、系统的消息忽略
                if(message.getRetractionTime() != null || message.getType().equals(MessageType.SYS_MSG) || message.getType().equals(MessageType.UPDATE_USER_GROUP_NAME_SYS_MSG)){
                    continue;
                }

                if (!Strings.isNullOrEmpty(message.getContent()) || !Strings.isNullOrEmpty(message.getFilePath())) {
                    Boolean result = Boolean.FALSE;

                    // 文字匹配聊天内容
                    if (!Strings.isNullOrEmpty(message.getContent())) {
                        Matcher contentMatcherContent = pattern.matcher(message.getContent());
                        result = contentMatcherContent.find();
                    }

                    // 图片、文件匹配文件名
                    if (!Strings.isNullOrEmpty(message.getFilePath())) {
                        Matcher filepathMatcherContent = pattern.matcher(message.getFilePath());
                        result = filepathMatcherContent.find();
                    }

                    //进行根据参数type和content（模糊查询）
                    if (result) {
                        //根据type不同返回不同的数据
                        if (messageVo.getType().equals(MessageType.ALL)) {
                            if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                                String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                                messagesList.get(i).setFilePath(substring);
                            }
                            if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                                // 图片路径前要拼接url前缀
                                message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                            }
                            newMessagesList.add(message);
                            continue;
                        }
                        if (messageVo.getType().equals(MessageType.FILE) && message.getType().equals(MessageType.FILE)) {
                            if (!Strings.isNullOrEmpty(message.getFilePath())) {
                                String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                                messagesList.get(i).setFilePath(substring);
                            }
                            newMessagesList.add(message);
                        }
                    }
                }
            }
            //进行list集合排序（升序）
            newMessagesList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newMessagesList);
            return serviceResult;
        }
    }

    /**
     * 根据参数fromUserAccount、toUserAccountinit、Row和direction，获取用户的某个聊天记录的上下文记录，并按照创建时间降序排列，分别支持向上和向下分页显示
     *
     * @param fromUserAccount
     * @param toUserAccount
     * @param initRow
     * @param direction
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public ServiceResult<List<Message>> redisContextPage(String fromUserAccount, String toUserAccount, Integer id, Integer initRow, Integer direction, Integer pageSize, Integer pageNo, Integer timeout) {
        ServiceResult<List<Message>> serviceResult = new ServiceResult<>();
        int start = pageSize * (pageNo - 1);
        //去chatPair表中 查询到 对应的code
        ChatPair chatPair = chatPairMapper.findByFromUserAccountAndToUserAccount(fromUserAccount, toUserAccount);
        if (chatPair == null) {
            List<Message> messagesList = new ArrayList<>();
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(messagesList);
            return serviceResult;
        }

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, pageSize, chatPair.getCode(), chatPair.getContentInvisibleTime(), timeout);

        //数据序列化
        List<Message> messagesList = modelHandler.toMessageList(stringSet, fromUserAccount);
        //根据当前数据向下展示
        if (direction.equals(MessageContext.DOWN)) {
            List<Message> messageDownList;
            if (messagesList.size() > initRow) {
                messageDownList = messagesList.subList(initRow, messagesList.size());
                for (int i = 0; i < messageDownList.size(); i++) {
                    Message message = messageDownList.get(i);
                    if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messageDownList.get(i).setFilePath(substring);
                    }
                    if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    messageDownList.set(i, message);
                }
            } else {
                messageDownList = messagesList;
                for (int i = 0; i < messageDownList.size(); i++) {
                    Message message = messageDownList.get(i);
                    if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messageDownList.get(i).setFilePath(substring);
                    }
                    if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    messageDownList.set(i, message);
                }
            }
            //进行list集合排序（升序）
            messageDownList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(messageDownList);
            return serviceResult;
        } else {
            //根据当前数据向上展示UPWARD
            List<Message> messageUpwardList;
            if (messagesList.size() > initRow) {
                messageUpwardList = messagesList.subList(0, initRow + 1);
                for (int i = 0; i < messageUpwardList.size(); i++) {
                    Message message = messageUpwardList.get(i);
                    if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messageUpwardList.get(i).setFilePath(substring);
                    }
                    if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    messageUpwardList.set(i, message);
                }
            } else {
                messageUpwardList = messagesList.subList(0, messagesList.size());
                for (int i = 0; i < messageUpwardList.size(); i++) {
                    Message message = messageUpwardList.get(i);
                    if (message.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        String substring = message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1);
                        messageUpwardList.get(i).setFilePath(substring);
                    }
                    if (message.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(message.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        message.setFilePath(pictureParamConfig.getUrlprefix() + message.getFilePath());
                    }
                    messageUpwardList.set(i, message);
                }
            }
            //进行list集合排序（升序）
            messageUpwardList.sort(Comparator.comparing(Message::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(messageUpwardList);
            return serviceResult;
        }
    }

    /**
     * 根据请求参数从redis中获取需要的数据
     *
     * @param start                指定开始位置
     * @param pageSize             查询数据数量
     * @param code                 每个聊天对的代码
     * @param contentInvisibleTime 内容不可见时间
     * @return 返回查询结果
     */
    private Set<String> getRedisDataByParam(long start, long pageSize, Integer code, Date contentInvisibleTime, Integer timeout) {
        Set<String> stringSet;

        long startScore;
        long endScore = System.currentTimeMillis();

        // 获取指定时间前的时间
        Date leftDate = DateUtils.getLeftDateByTime(timeout);

        // 若用户设置了内容不可见时间，查询聊天记录时查询此时间及之后的数据，否则查询所有数据
        if (contentInvisibleTime != null) {
            // 判断内容不可见时间如果早于15天前的时间，则查询开始时间为15天前的时间
            if (contentInvisibleTime.compareTo(leftDate) < 0) {
                startScore = leftDate.getTime();
            } else {
                startScore = contentInvisibleTime.getTime();
            }
        } else {
            startScore = leftDate.getTime();
        }

        stringSet = redisManager.zReverseRangeByScore(RedisStorage.MESSAGE_PREFIX + code, startScore, endScore, start, pageSize);
        return stringSet;
    }

    /**
     * 恢复未读消息，先在message表中通过fromUserAccount对toUserAccount修改消息状态，toUserAccount发送到消息服务器上。
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Integer> restoreMessage(String fromUserAccount, String toUserAccount) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        UpdateWrapper<Message> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.FROM_USER_ACCOUNT_FIELD, fromUserAccount);
        updateWrapper.eq(Constants.TO_USER_ACCOUNT_FIELD, toUserAccount);
        updateWrapper.eq(Constants.READ,MessageType.UNREAD);
        Message message = new Message();
        message.setReadTime(new Date());
        message.setRead(MessageType.READ);
        int update = messageMapper.update(message, updateWrapper);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(update);
        return serviceResult;
    }

    /**
     * 查询未读消息id集合
     * @param fromUserAccount 发送消息的人
     * @param toUserAccount   接收消息的人
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<String>> getUnreadMsgList(String fromUserAccount, String toUserAccount) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();

        // 查询未读消息id集合
        List<String> result = messageMapper.getUnreadMsgList(fromUserAccount, toUserAccount);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 撤回消息
     * @param id       账号id
     * @param dateTime 撤回时间
     */
    @Override
    public RetractionPojo retractionMessage(Integer id, Integer dateTime) {
        RetractionPojo retractionPojo = new RetractionPojo();
        long lt = new Long(dateTime);
        lt = lt * 1000;
        Date date = new Date(lt);
        UpdateWrapper<Message> messageUpdateWrapper = new UpdateWrapper<>();
        messageUpdateWrapper.eq("id", id);
        Message message = new Message();
        message.setRetractionTime(date);
        messageMapper.update(message, messageUpdateWrapper);
        Message messageData = messageMapper.selectOne(messageUpdateWrapper);
        retractionPojo.setType(1);
        retractionPojo.setMessage(messageData);
        return retractionPojo;
    }

    /**
     * 将message表中的数据导入redis
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<Boolean> importMessageIntoRedis() {
        ServiceResult<Boolean> returnResult = new ServiceResult<>();

        List<Message> messageList = findAllOrderByCreateTimeDesc();
        if (null != messageList && messageList.size() > 0) {
            log.info("开始导入message数据");
            for (Message message : messageList) {
                ChatPair chatPair = findByFromUserAccountAndToUserAccount(message.getFromUserAccount(), message.getToUserAccount());
                if (null == chatPair) {
                    log.warn("不存在from_user_account为[{}],to_user_account为[{}]的记录", message.getFromUserAccount(), message.getToUserAccount());
                    continue;
                }

                // 数据添加到redis中key为MESSAGE:code
                redisManager.zAdd(RedisStorage.MESSAGE_PREFIX + chatPair.getCode(), JSON.toJSONString(message), message.getCreateTime().getTime());
//                redisManager.expire(RedisStorage.MESSAGE_PREFIX + chatPair.getCode(), redisParamConfig.getTimeout());
            }
        }

        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 根据fromUserAccount和toUserAccount，查找ChatPair对象
     * @param fromUserAccount 发送消息的用户账号
     * @param toUserAccount 接收消息的用户账号
     * @return 返回聊天对数据
     */
    public ChatPair findByFromUserAccountAndToUserAccount(String fromUserAccount, String toUserAccount) {
        ChatPair chatPair = new ChatPair();
        chatPair.setFromUserAccount(fromUserAccount);
        chatPair.setToUserAccount(toUserAccount);
        QueryWrapper<ChatPair> queryWrapper = new QueryWrapper<>(chatPair);
        return chatPairMapper.selectOne(queryWrapper);
    }

    /**
     * 查询所有记录，按照创建时间降序排列
     * @return 返回查询结果
     */
    public List<Message> findAllOrderByCreateTimeDesc() {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        return messageMapper.selectList(queryWrapper);
    }
}